<?php
namespace Istat;

class MongoIstat 
{
	var $db;

	public function __construct($env = 'local', $database = 'eureka')
	{
		$server = 'mongodb://localhost/';
		if ($env == 'prod')
		{
			$server = "mongodb://fullo:eurek4@ds031637.mongolab.com:31637/".$database;
		}

		$mongodb = new \Mongo($server);
 
		$this->db = $mongodb->$database;
		
		$co = $this->db->territorio;
		$co->ensureIndex(array('geo' => '2d'));
  		$co->ensureIndex(array('geo' => 'geoHaystack', 'anno' => 1), array('bucketSize' => 0.1));
	}

	public function km2radius($radius = 0)
    {
            return $radius/111.12;
    }

	public function getPlaceByYear(array $geo = array(), $year = 2009, $radius = 10, $type = false)
	{
		
		 $search['anno'] = $year;
			
		 if ($type) $search['type'] = $type;

		 $command = array( 'geoSearch' => 'territorio', 'near' => $geo, 'maxDistance' => $radius, 'search' => $search );
	  	 $results = $this->db->command($command);

		return (is_array($results))?$results['results']:array();
	}

    public function getPlaceByGeo(array $geo = array(), $radius = 10)
    {
      return iterator_to_array($this->db->territorio->find( array( 'geo' => array( '$near' => $geo, '$maxDistance' => $radius))));
    }    

    public function getPlaces(array $params = array())
    {
       return iterator_to_array(
            $this->db->territorio->find($params)
       );    
    }
    


}
